import 'package:flutter/material.dart';
import '../../l10n/app_localizations.dart';
import '../../manger/cached_image_widget.dart';
import '../../manger/network_utils.dart';
import '../../models/message_model.dart';
import '../../components/toast_utils.dart';
import '../../components/custom_dialog.dart';

class DyInputView extends StatefulWidget {
  final VoidCallback onClickCheckNext;
  final VoidCallback onDyClickShowList;
  final bool isShowMemberIcon;
  final String blurb;
  final String title;
  DyInputView({
    super.key,
    required this.onClickCheckNext,
    required this.onDyClickShowList,
    required this.isShowMemberIcon,
    required this.blurb,
    required this.title,
  });

  @override
  State<DyInputView> createState() => DyInputViewState();
}

class DyInputViewState extends State<DyInputView> {
  bool sureId = false;
  bool isNext = false;
  bool showIconView = false;
  String dyId = '';
  String dyImageUrl = '';
  String dyName = '';
  final TextEditingController inputController = TextEditingController();
  final FocusNode inputFocusNode = FocusNode();

  @override
  void dispose() {
    inputController.dispose();
    inputFocusNode.dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            const Text('*', style: TextStyle(color: Color(0xFFFF0000))), // titleRedColor
            const SizedBox(width: 5),
            Text(widget.title, style: TextStyle(color: Colors.black, fontSize: 15)), // label2Color
            const Spacer(),
            GestureDetector(
              onTap: _onLabelTapped,
              child: Text(
                AppLocalizations.of(context)!.howToCheckATikTokID,
                style: TextStyle(color: Color(0xFF5D5FEE), fontSize: 14), // titleBlueColor
                textAlign: TextAlign.right,
              ),
            ),
          ],
        ),
        const SizedBox(height: 10),
        if (!showIconView) _buildInputView(),
        if (showIconView) _buildIconView(),
      ],
    );
  }

  Widget _buildInputView() {
    return Row(
      children: [
        Container(
          padding: const EdgeInsets.only(left: 10, right: 20),
          height: 40,
          width: MediaQuery.of(context).size.width - 180,
          decoration: BoxDecoration(
            color: Colors.white,
            border: Border.all(color: Color(0xFFE6E6E6)), // mainBgColor
            borderRadius: BorderRadius.circular(5),
          ),
          child: Row(
            children: [
              Expanded(
                child: TextField(
                  controller: inputController,
                  focusNode: inputFocusNode,
                  style: TextStyle(fontSize: 14),
                  decoration: InputDecoration.collapsed(
                    hintText: widget.blurb,
                    hintStyle: TextStyle(color: Color(0xFFACACAC)),
                  ),
                  onChanged: (value) {
                    setState(() {
                      dyId = value;
                    });
                  },
                ), 
              ),  
              widget.isShowMemberIcon
              ? GestureDetector(
                  onTap: () {
                    widget.onDyClickShowList.call(); // 正确调用onTap回调
                  },
                  child: Image.asset('assets/images/order_icon5.png', width: 20, height: 20),
                )
              : const SizedBox()
            ],
          ),
        ),
        const SizedBox(width: 10),
        Container(
          height: 34,
          width: 100,
          decoration: BoxDecoration(
            gradient: inputController.text.isNotEmpty 
              ? const LinearGradient(
                  colors: [Color(0xFF8A9CFF), Color(0xFF5F60EF)],
                )
              : null,
            color: inputController.text.isEmpty ? const Color(0xFFC2C3FF) : null,
            borderRadius: BorderRadius.circular(18),
          ),
          child: TextButton(
            onPressed: clickConfirm,
            style: TextButton.styleFrom(padding: EdgeInsets.zero),
            child: Text(AppLocalizations.of(context)!.confirmAccount, style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
          ),
        ),
      ],
    );
  }

  Widget _buildIconView() {
    return Container(
      height: 60,
      padding: const EdgeInsets.symmetric(horizontal: 10),
      decoration: BoxDecoration(
        border: Border.all(color: Color(0xFFE6E6E6)), // mainBgColor
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(20),
            child: CachedImage(
              imageUrl: dyImageUrl,
              width: 40,
              height: 40,
              placeholderPath: 'assets/images/placeholderImage.png',
            ),
          ),

          const SizedBox(width: 10),
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(dyName, style: TextStyle(color: Color(0xFF333333), fontWeight: FontWeight.bold, fontSize: 15)), // label2Color
              Text('抖音号：$dyId', style: TextStyle(color: Color(0xFF666666), fontSize: 13)), // label666Color
            ],
          ),
          const Spacer(),
          GestureDetector(
            onTap: _clickSwitch,
            child: Row(
              children: [
                Image.asset('assets/images/切换.png', width: 18, height: 20),
                SizedBox(width: 1),
                Text(AppLocalizations.of(context)!.switchAccount, style: TextStyle(color: Color(0xFF5D5FEE), fontSize: 13)),
              ],
            ),
          ),
        ],
      ),
    );
  }

  void clickConfirm() async{
    // 此处留空逻辑，参考原 iOS 中是弹窗验证
    if (!sureId) {
      try {
      final response = await NetworkUtils.post(
        RequestCmd.check,
        body: {"account": dyId, "type": 1},
      );

      final model = CheckModel.fromJson(response);
      if (model.code == 200) {
        if (model.data != null) {
          setState(() {
            showIconView = true;
            dyImageUrl = model.data!.avatarThumb;
            sureId = true;
            dyName = model.data!.nickName;
            dyId = model.data!.tiktokId;
            if (isNext) {
              widget.onClickCheckNext();
            }
          });
        }
       
      } else if (model.code == 10042) {
      showDialog(
          context: context,
          builder: (context) => CustomDialog(
            title: AppLocalizations.of(context)!.warmTips,
            description: "${AppLocalizations.of(context)!.dyInputText1}$dyId, ${AppLocalizations.of(context)!.dyInputText2}",
            leftButtonText: AppLocalizations.of(context)!.goModify,
            rightButtonText: AppLocalizations.of(context)!.confirmCorrect,
            onLeftPressed: () {
              Navigator.pop(context);
              setState(() {
                sureId = false;
                showIconView = false;
                inputController.text = dyId;
              });
                WidgetsBinding.instance.addPostFrameCallback((_) {
                  if (mounted && inputFocusNode.canRequestFocus) {
                    inputFocusNode.requestFocus();
                  }
                });   
              },
            onRightPressed: () {
              Navigator.pop(context);
              setState(() {
                dyImageUrl = "";
                sureId = true;
                showIconView = true;
                dyName = dyId;
                if (isNext) {
                  widget.onClickCheckNext();
                }             
              });
            },
          ),
        );
      } else {
        ToastUtils.showCenterToast(context, model.msg);
        setState(() {
          sureId = false;
        });
      }
    } catch (e) {
      ToastUtils.showCenterToast(context, "ID${AppLocalizations.of(context)!.cannotBeEmpty}");
      print(e);
    }
    }

   
  }

  void _clickSwitch() {
    setState(() {
      sureId = false;
      showIconView = false;
    });
  }

  void _onLabelTapped() {
    showDialog(
      context: context,
      builder: (_) => Dialog(
        child: Image.network(
          "https://m.test.94lives.com/_nuxt/img/chakandy.608201b.png",
          errorBuilder: (_, __, ___) => const Icon(Icons.error),
        ),
      ),
    );
  }
}
